<template>
  <div :class="{'mobile-create mobile-settle-info': showMobilePage,'mb2': process === 0}" class="settle-info-container">
    <div class="supplier-title">
      <Title :style="{marginBottom: process === 0 ? '12px' : '5px'}" title="结算信息" />
      <div v-if="isInvite" class="supplier-tips">注意：无法选择需要结算的订单可以在【付款申请】时邀请他人填写。</div>
    </div>
    <el-row :gutter="8">
      <el-form
        ref="formRef"
        :class="{'mobile-el-form': showMobilePage, 'el-form-dividing': !showMobilePage && process !== 0,'gray-label': !(isDiySelectSupplier && process === 0)}"
        :label-width="showMobilePage?'100px':'110px'"
        :model="stepOneData"
        :rules="rules"
        :label-position="showMobilePage?'left':'right'">
        <el-col v-if="isDiySelectSupplier" :span="colSpan" class="supplier-info-item">
          <el-form-item :label="`供应商来源${process === 0?'':'：'}`" :style="itemStyle" class="isRequired mobile-create-item">
            <selectWithoutHttp
              v-if="process === 0"
              v-model="stepOneData.pageFrom"
              :list-data="pageFromOptions"
              key-name="id"
              label-name="name"
              class="width240"
              @change="pageFromChange"
            />
            <ToolTip v-else :content="supplierSourceName[stepOneData.pageFrom] || '--'" />
          </el-form-item>
        </el-col>
        <el-col :span="colSpan" class="supplier-info-item">
          <el-form-item :label="`供应商名称${process === 0?'':'：'}`" :style="itemStyle" class="isRequired" prop="supplierId">
            <!-- 自选供应商 -->
            <SelectWithUserLoad
              v-if="resetFlag && process === 0 && isDiySelectSupplier"
              v-model="stepOneData.supplierId"
              :loadmore-method="getSupplier()"
              :hide-select-list="supplierData.supplierId ?[{id: supplierData.supplierId, supplier:supplierData.supplier}]:[]"
              :collapse-tags="false"
              open-tool-tip
              key-name="id"
              label-name="supplier"
              filterable
              class="width240"
              @changeMethod="supplierChange($event)"
            />
            <ToolTip v-else :content="supplierData.supplier" />
          </el-form-item>
        </el-col>
        <el-col v-if="process !== 0" :span="colSpan" class="supplier-info-item">
          <el-form-item :style="itemStyle" label="成本来源：">
            <span class="content">{{ `${supplierCostBelong(stepOneData.costBelong)}${isInvite ? '(协作)' : ''}` }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="colSpan" class="supplier-info-item">
          <!-- todo 结算方式选择 -->
          <el-form-item :label="`结算方式${process === 0?'':'：'}`" :style="itemStyle" class="mobile-create-item" prop="settlementMethod">
            <div v-if="process === 0" class="flex-center">
              <selectWithoutHttp
                v-model="stepOneData.settlementMethod"
                :list-data="settleOptions"
                key-name="id"
                label-name="name"
                class="width240"
                @change="settleOptionChange"
              />
              <tipIcon :content="settleMethodTip" :img-height="16" :img-width="16" max-width="350px" use-html class="ml8"/>
            </div>
            <ToolTip v-else :content="stepOneData.settlementMethod === 1 ? '一次结算' : '多次结算'" />
          </el-form-item>
        </el-col>
        <el-col :span="colSpan" class="supplier-info-item">
          <el-form-item :label="`协作方式${process === 0?'':'：'}`" :style="itemStyle" class="mobile-create-item" prop="isInvite">
            <!-- todo 协作方式选择 -->
            <template v-if="process === 0">
              <el-radio-group v-model="stepOneData.isInvite" @change="inviteOptionChange">
                <el-radio :label="false" class="fb-radio">非协作</el-radio>
                <el-radio :label="true" class="fb-radio">协作</el-radio>
              </el-radio-group>
            </template>
            <ToolTip v-else :content="stepOneData.isInvite ? '协作' : '非协作'" />
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import Title from '@/components/Title';
import SelectWithUserLoad from '@/components/Common/selectWithUserLoad';
import SelectWithoutHttp from '@/components/Common/selectWithoutHttp';
// filters
import { supplierCostBelong } from '@/filters/status';
// api
import { supplierManageList, supplierInfo } from '@/api/supplier';
import { getMengliSuppliers } from '@/api/mengli';

export default {
  components: { Title, SelectWithUserLoad, SelectWithoutHttp },
  model: {
    prop: 'stepOneData',
    event: 'changeValue'
  },
  props: {
    stepOneData: {
      type: Object,
      default: () => {
        return {
          pageFrom: null, // 供应商来源
          supplierId: '' // 供应商id
        };
      }
    },
    process: {
      type: String | Number,
      default: null
    }
  },
  data() {
    return {
      settleOptions: [
        { id: 1, name: '一次结算' },
        { id: 0, name: '多次结算' }
      ],
      resetFlag: true,
      supplierData: {},
      isDiySelectSupplier: false // 是否自选供应商
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    rules() {
      if (this.process !== 0) return {};
      return {
        'settlementMethod': [{ required: true, trigger: 'change', validator: this.validate('请选择结算方式') }],
        'isInvite': [{ required: true, trigger: 'change', validator: this.validate('请选择协作方式') }],
        'supplierId': [{ required: true, trigger: 'change', validator: this.validate('请选择供应商名称') }]
      };
    },
    isInvite() {
      return this.stepOneData.isInvite;
    },
    isDetail() {
      return this.$route.name === 'supplierDetail';
    },
    pageFromOptions() {
      return [
        { id: 'saleSupplier', name: '飞博供应商' },
        { id: 'mengliSupplier', name: '萌力供应商' }
      ];
    },
    supplierSourceName() {
      return {
        'saleSupplier': '飞博供应商',
        'mengliSupplier': '萌力供应商'
      };
    },
    colSpan() {
      return this.process === 0 ? 12 : 8;
    },
    itemStyle() {
      return this.process === 0 ? '' : 'margin-bottom: 0';
    },
    settleMethodTip() {
      return `<div class="mb5">一次结算：仅进行一次审批，实付金额必须等于订单结算总金额</div><div>多次结算：可发起多次审批，多次审批单的实付金额之和必须等于订单结算总金额</div>`;
    }
  },
  created() {
    if (this.stepOneData.supplierId) {
      this.getSupplierInfo();
      this.isDiySelectSupplier = false;
    } else {
      this.isDiySelectSupplier = true;
    }
  },
  methods: {
    supplierCostBelong,
    /**
     * 获取供应商下拉项
     */
    getSupplier() {
      const pageFrom = this.stepOneData.pageFrom;
      const a = function(params) {
        return new Promise((resolve, reject) => {
          params.supplier = '';
          params.keyword = '';
          if (params.userName) {
            if (pageFrom === 'saleSupplier') {
              params.supplier = params.userName;
            } else {
              params.keyword = params.userName;
            }
          }
          const getFun = pageFrom === 'saleSupplier' ? supplierManageList : getMengliSuppliers;
          getFun(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return a;
    },

    // 获取供应商详情
    getSupplierInfo(init = false) { // 从供应商管理页面进入跳转获取供应商信息
      const supplierId = this.stepOneData.supplierId;
      supplierInfo(supplierId, { costBelong: this.stepOneData.costBelong }).then(res => {
        if (res.code === 200) {
          this.supplierData = res.data;
          this.supplierData.supplierId = supplierId;
        }
        init && this.$emit('changeValue', this.stepOneData);
      });
    },
    pageFromChange() {
      this.stepOneData.supplierId = '';
      this.$emit('changeValue', this.stepOneData);
      this.resetFlag = false;
      this.$nextTick(() => {
        this.resetFlag = true;
      });
    },
    supplierChange(item) {
      this.stepOneData.supplierName = item.supplier;
      this.stepOneData.hasRate = item.hasRate;
      this.stepOneData.supplierPriceRate = item.priceRate;
      this.$emit('changeValue', this.stepOneData);
    },
    inviteOptionChange(option) {
      this.$emit('changeValue', this.stepOneData);
    },
    settleOptionChange() {
    },
    validate(msg) {
      return (rule, value, callback) => {
        if (!value && value !== false && value !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    },
    validateForm() {
      return new Promise((resolve, reject) => {
        this.$refs.formRef.validate(valid => {
          if (valid) {
            resolve(valid);
          } else {
            reject(false);
          }
        });
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.settle-info-container {
  margin: 16px 0;
  padding: 0px 24px;
}
.mb2 {
  margin-bottom: 2px !important;
}
.supplier-info-item {
  & ::v-deep {
    .el-form-item__label {
      font-size: 14px;
      color: #999;
      line-height: 30px;
    }
    .el-form-item__content {
      line-height: 30px;
      color: #333;
    }
  }
  .content {
    font-size: 14px;
    color: #333333;
  }
}

.mobile-settle-info {
  margin: 0 !important;
  padding: 12px !important;
  .mobile-create-item {
    margin-bottom: 12px !important;
  }
  .mobile-el-form {
    padding-left: 10px !important;
  }
  .gray-label {
    ::v-deep .el-form-item__label {
      color: #999999 !important;
    }
  }
}
.supplier-title {
  @include flexStyle($align: center, $justify: flex-start);
  &::v-deep {
    .title-head {
      flex: unset;
    }
  }
  .supplier-tips {
    font-size: 12px;
    color: #999;
    margin: 0 0 14px 10px;
  }
}
.width240 {
  width: 240px;
  ::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
</style>
